/**
* @Author: zou.yingbin
* @Create  : 2020/9/14 10:56
* @Modify  : 2020/9/14 10:56
 */

package main

import (
	"time"

	"sync"
)

type reqDetail struct {
	loginId string
	label   string
	tReq    time.Time
	tRsp    time.Time
	tSpan   int64
}

type stReqLog struct {
	mLock   sync.RWMutex
	mDetail map[uint32]reqDetail
}

var (
	valReqLog *stReqLog
)

func (r *stReqLog) AddRequest(loginId, label string, serialNum uint32) {
	r.mLock.Lock()
	defer r.mLock.Unlock()

	d := reqDetail{
		loginId: loginId,
		label:   label,
		tReq:    time.Now().Local(),
	}

	r.mDetail[serialNum] = d
}

func (r *stReqLog) AddRespond(serialNum uint32) {
	r.mLock.RLock()
	defer r.mLock.RUnlock()

	t, ok := r.mDetail[serialNum]
	if ok {
		t.tRsp = time.Now().Local()
		diff := t.tRsp.Sub(t.tReq)
		t.tSpan = diff.Milliseconds()
		if valLog != nil {
			valLog.Logger().Debugf("%s,%s,%s,%s,%d\n",
				t.loginId, t.label, t.tReq.Format("15:04:05.000"),
				t.tRsp.Format("15:04:05.000"), t.tSpan)
		}
	}
}

func InitReqLog() {
	valReqLog = new(stReqLog)
	valReqLog.mDetail = map[uint32]reqDetail{}
}
